# 自定义元类控制类的实例化


# 单例模式
class MySQL:
    __instance = None  # 单例对象

    def __init__(self):
        self.host = '127.0.0.1'
        self.port = 3306

    @classmethod
    def singleton(cls):
        if not cls.__instance:
            obj = cls()
            cls.__instance = obj
        return cls.__instance


# 元类实现单例模式
class MyMeta(type):  # 1. 继承type
    def __init__(self, class_name, class_base, class_dic):
        # 判断类名的首字母是否大写
        if not class_name.istitle():
            raise TypeError('类名的首字母必须大写')
        # __doc__ 类的注释检查
        if '__doc__' not in class_dic or not class_dic['__doc__'].stript():
            raise TypeError('必须有注释， 且注释不能为空')
        # 调用父类方法
        super(MyMeta, self).__init__(class_name, class_base, class_dic)
        # 单例对象
        self.__instance = None

    # __call__ 内置方法控制类对象的创建行为
    def __call__(self, *args, **kwargs):
        # 1.创建单例对象self.__instance
        if not self.__instance:
            obj = object.__new__(self)
            # 2.初始化单例对象
            self.__init__(obj)
            self.__instance = obj
        # 3.返回单例对象
        return self.__instance


class Mysql(object, metaclass=MyMeta):
    """
    mysql 单例
    """
    __instance = None  # 单例对象

    def __init__(self):
        self.host = '127.0.0.1'
        self.port = 3306

    @classmethod
    def singleton(cls):
        if not cls.__instance:
            obj = cls()
            cls.__instance = obj
        return cls.__instance


mysql_1 = Mysql()
mysql_2 = Mysql()
mysql_3 = Mysql()
